package com.glodon.paas.databag.biz.impl;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.glodon.paas.databag.biz.ThumbnailBiz;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.UUIDUtil;

@Component
public class ThumbnailBizImpl implements ThumbnailBiz {
    private final Logger logger = LoggerFactory.getLogger(ThumbnailBizImpl.class);
    private final int DEFAULT_THUMBNAIL_WIDTH = 64;
    private final int DEFAULT_THUMBNAIL_HEIGHT = 64;
    @Value("${databag.image.thumbnail}")
    private String imageThumbnail;
    private int[][] thumbnailSize;

    @Override
    public BufferedImage createThumbnail(InputStream is) {
        return createThumbnail(is, DEFAULT_THUMBNAIL_WIDTH, DEFAULT_THUMBNAIL_HEIGHT);
    }

    @Override
    public BufferedImage createThumbnail(InputStream is, int width, int height) {
        BufferedImage image = null;
        try {
            image = ImageIO.read(is);
        } catch (IOException e) {
            logger.error("cann't read image input stream.", e);
            throw PaasServerExceptionFactory.systemException("cann't read image input stream.", e);
        }
        int sWidth = image.getWidth();
        int sHeight = image.getHeight();
        double scaleRate = Math.min((double) width / sWidth, (double) height / sHeight);
        int dWidth = (int) (sWidth * scaleRate);
        int dHeight = (int) (sHeight * scaleRate);
        Image scaledImage = image.getScaledInstance(dWidth, dHeight, Image.SCALE_SMOOTH);
        BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        int x = (width - dWidth) / 2;
        int y = (height - dHeight) / 2;
        Graphics2D g = target.createGraphics();
        target = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        g = target.createGraphics();
        g.drawImage(scaledImage, x, y, null);
        g.dispose();
        return target;
    }

    @Override
    public List<String> createImageDatabag(String inputFile, String tempPath) {
        List<String> result = new ArrayList<String>();
        try {
            String uuid = UUIDUtil.getUUIDStr();
            String fileName = parseFileName(inputFile);
            for (int i = 0; i < thumbnailSize.length; i++) {
                InputStream is = new FileInputStream(inputFile);
                BufferedImage thumbnail = createThumbnail(is, thumbnailSize[i][0], thumbnailSize[i][1]);
                StringBuffer sb = new StringBuffer();
                String resource = sb.append("resource").append("/").append(uuid).append("/").append(fileName).append("-")
                        .append(thumbnailSize[i][0]).append("x").append(thumbnailSize[i][1]).append(".png").toString();
                File file = new File(tempPath + File.separator + resource);
                File parentFile = file.getParentFile();
                if (parentFile != null && !parentFile.exists()) {
                    parentFile.mkdirs();
                }
                file.createNewFile();
                ImageIO.write(thumbnail, "png", file);
                result.add(resource);
                // FIXME close stream
            }
        } catch (IOException e) {
            logger.error("saving thumbnail databag failed.", e);
            throw PaasServerExceptionFactory.systemException("saving thumbnail databag failed.", e);
        }
        return result;
    }

    private String parseFileName(String file) {
        String name = new File(file).getName();
        int suffixIndex = name.lastIndexOf(".");
        if (suffixIndex == -1) {
            suffixIndex = name.length();
        }
        return name.substring(0, suffixIndex);
    }

    @PostConstruct
    public void parseImageThumbnailSize() {
        String[] sizeCount = imageThumbnail.split(",");
        thumbnailSize = new int[sizeCount.length][];
        for (int i = 0; i < sizeCount.length; i++) {
            String[] wh = sizeCount[i].split("x");
            thumbnailSize[i] = new int[] { Integer.parseInt(wh[0].trim()), Integer.parseInt(wh[1].trim()) };
        }
    }

    public void setThumbnailSize(int[][] thumbnailSize) {
        this.thumbnailSize = thumbnailSize;
    }
}
